﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interfaces;
using System.IO;
using NCalc;

namespace KOSHI_FileDAO
{
    public class FileDAO : IKoshiDAO
    {
        public string TaskFile { get; set; }
        public string SolutionFile { get; set; }
        public int RoundDecimals { get; set; }

        public FileDAO(string TaskFile, string SolFile)
        {
            if (TaskFile == null || SolFile == null)
            {
                throw new ArgumentNullException();
            }
            this.RoundDecimals = 5;
            this.TaskFile = TaskFile;
            this.SolutionFile = SolFile;
        }

        public KoshiDE.KoshiTask LoadTask()
        {
            if (!File.Exists(this.TaskFile))
            {
                throw new FileNotFoundException();
            }

            string[] lines = File.ReadAllLines(this.TaskFile);
            double[] data = lines[0].Split(' ').Select((x) => (double.Parse(x))).ToArray();

            return new KoshiDE.KoshiTask(data[0], data[1], data[2], data[3], delegate(double x, double y) 
                {
                    Expression exp = new Expression(lines[1]);
                    exp.Parameters["x"] = x;
                    exp.Parameters["y"] = y;

                    return (double)exp.Evaluate();
                });
        }

        public void SaveSolution(KoshiDE.KoshiSolution solution)
        {
            string[] wr_data = new string[solution.Length+1];
            wr_data[0] = "Point Value";
            for (int i = 1; i <= solution.Length; i++)
            {
                wr_data[i] = string.Format("{0} {1}", solution.Points[i-1], Math.Round(solution[solution.Points[i-1]],this.RoundDecimals));
            }
            File.WriteAllLines(this.SolutionFile, wr_data);
        }
    }
}
